package com.pz.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.pz.mapper.UserMapper;
import com.pz.pojo.User;
import com.pz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/** @author：PZ @Date: 2020/11/4 14 35 */
@Controller
public class UserController {

  @Autowired UserService userService;
  @Resource
  UserMapper userMapper;

  @PostMapping("/user/login")
  public String loginUser(String name, String password, HttpSession session, Model m) {
    User user = userService.login(name, password);
    if (user == null) {
      m.addAttribute("tip", "账号或密码错误");
      return "admin/login";
    }
    session.setAttribute("user", user);
    return "redirect:/admin/blogs";
  }

  @PostMapping("/user/register")
  public String register(String name, String password, HttpSession session, Model m) {
//    User user = userService.login(name, password);
    User user = new User();
    user.setName(name);
    List<User> users = userMapper.selectList(user);
    if(users==null||users.size()==0){
//      没有这个用户名的人
      user.setPassword(DigestUtil.md5Hex(password));
      userMapper.insert(user);
    }else{
      m.addAttribute("tip", "已经注册过了 用户名: "+name);
    }

//    if (user == null) {
//      m.addAttribute("tip", "账号或密码错误");
//      return "admin/login";
//    }
//    session.setAttribute("user", user);
    return "admin/login";
//    return "redirect:/admin/blogs";
  }

  @GetMapping("/user/logout")
  public ModelAndView logOut(HttpSession session) {
    ModelAndView m = new ModelAndView();
    session.removeAttribute("user");
    m.addObject("message", "用户已退出");
    m.setViewName("/admin/tip");
    return m;
  }
}
